package com.wsc.wisdomchinaqinghe.fragment;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.stx.xhb.mylibrary.XBanner;
import com.umeng.analytics.MobclickAgent;
import com.wsc.wisdomchinaqinghe.R;
import com.wsc.wisdomchinaqinghe.Tools.JsonTools;
import com.wsc.wisdomchinaqinghe.Tools.Tools;
import com.wsc.wisdomchinaqinghe.activitity.HomeActivity;
import com.wsc.wisdomchinaqinghe.activitity.InfoDetailActivity;
import com.wsc.wisdomchinaqinghe.activitity.LifeServerActivity;
import com.wsc.wisdomchinaqinghe.activitity.Login_RegisterActivity;
import com.wsc.wisdomchinaqinghe.activitity.ReceptionCenterActivity;
import com.wsc.wisdomchinaqinghe.activitity.ShangjiaCuXiaoActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.FloorEventActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.PeopleControlActivity;
import com.wsc.wisdomchinaqinghe.activitity.fourmodule.PeopleControlPublishActivity;
import com.wsc.wisdomchinaqinghe.adapter.FourModuleNewAdapter;
import com.wsc.wisdomchinaqinghe.adapter.LookListAdapter;
import com.wsc.wisdomchinaqinghe.application.MyApplication;
import com.wsc.wisdomchinaqinghe.callback.ClickIntoFragment;
import com.wsc.wisdomchinaqinghe.callback.ContributorView;
import com.wsc.wisdomchinaqinghe.constant.Constant;
import com.wsc.wisdomchinaqinghe.javaBean.HomeBanner;
import com.wsc.wisdomchinaqinghe.javaBean.HomeModule;
import com.wsc.wisdomchinaqinghe.javaBean.LookHomeNews;
import com.wsc.wisdomchinaqinghe.javaBean.RespObj;
import com.wsc.wisdomchinaqinghe.javaBean.StreetInfoListBean;
import com.wsc.wisdomchinaqinghe.presenter.ContributorPresenter;
import com.wsc.wisdomchinaqinghe.view.MyListView;
import com.wsc.wisdomchinaqinghe.view.iphoneDialogBuilder;

import java.util.ArrayList;
import java.util.List;


/**
 * 首页
 */
public class HomeFragment extends Fragment implements XBanner.XBannerAdapter, View.OnClickListener, ContributorView {

    List<HomeBanner> homeBannerList = new ArrayList<>();
    private XBanner fragment_first_bannera;//轮播控件
    private PullToRefreshScrollView fragment_first_scrollView;
    private Context context;
    private ContributorPresenter contributorPresenter;
    private final String HOME_BANNER = "HOME_BANNER";
    private final String FOUR_MODULE = "FOUR_MODULE";
    private final String EIGHT_MODULE = "EIGHT_MODULE";
    private final String HOME_NEWS = "HOME_NEWS";
    private GridView fragment_first_head_sida_gongnneg;
    private MyListView fragment_first_listView;
    private int skip = 0;
    private int limit = 10;
    private boolean isfresh = true;
    private LookListAdapter quanBuAdapter;
    private List<LookHomeNews> homeNewsList;
    private MyApplication myApplication;
    private LinearLayout fragment_first_sqzu_ckqb_llt;
    private ClickIntoFragment mCallBack;// 接口变量
    private boolean ishide = false;
    private List<HomeModule> homeModuleFourList;
    private List<HomeModule> homeModuleEightList;
    private TextView tv_headtitle;
    private StreetInfoListBean streetInfoListBean;
    private final String LOCATION_FLAG="LOCATION_FLAG";
    private String cidNumber;
    private String cidTitle;
    private LinearLayout layout;
    private ImageView iv_one;
    private TextView tv_titleone;
    private TextView tv_contentone;
    private ImageView iv_two;
    private TextView tv_titletwo;
    private TextView tv_contenttwo;
    private ImageView iv_three;
    private TextView tv_titlethree;
    private TextView tv_contentthree;
    private RelativeLayout layout_one;
    private RelativeLayout layout_two;
    private RelativeLayout layout_three;
    private View viewthree;
    private LinearLayout layout_threenew;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        context = getActivity();
        String locationString = Tools.getSharedPreferencesStrings(Constant.SharePreferenceLocation, "", context);
        if (locationString.length() > 0) {
            streetInfoListBean = JsonTools.jsonStringToObject(locationString, StreetInfoListBean.class);
            cidNumber=streetInfoListBean.getId();
            cidTitle=streetInfoListBean.getStreetName();
        }
        myApplication = (MyApplication) getActivity().getApplication();
        initView(view);
        contributorPresenter = new ContributorPresenter(this, context);
        return view;
    }

    private void initView(View view) {
//        layout=(LinearLayout) view.findViewById(R.id.layout);
//        layout.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent=new Intent(context, TestActivity.class);
//                startActivity(intent);
//            }
//        });
        viewthree=view.findViewById(R.id.viewthree);
        layout_threenew=(LinearLayout) view.findViewById(R.id.layout_threenew);
        iv_one= (ImageView) view.findViewById(R.id.iv_one);
        tv_titleone= (TextView) view.findViewById(R.id.tv_titleone);
        tv_contentone= (TextView) view.findViewById(R.id.tv_contentone);

        layout_one= (RelativeLayout) view.findViewById(R.id.layout_one);
        layout_two= (RelativeLayout) view.findViewById(R.id.layout_two);
        layout_three= (RelativeLayout) view.findViewById(R.id.layout_three);
        layout_one.setOnClickListener(this);
        layout_two.setOnClickListener(this);
        layout_three.setOnClickListener(this);

        iv_two= (ImageView) view.findViewById(R.id.iv_two);
        tv_titletwo= (TextView) view.findViewById(R.id.tv_titletwo);
        tv_contenttwo= (TextView) view.findViewById(R.id.tv_contenttwo);

        iv_three= (ImageView) view.findViewById(R.id.iv_three);
        tv_titlethree= (TextView) view.findViewById(R.id.tv_titlethree);
        tv_contentthree= (TextView) view.findViewById(R.id.tv_contentthree);

        tv_headtitle = (TextView) view.findViewById(R.id.tv_headtitle);
        if (cidTitle != null) {
            tv_headtitle.setText(cidTitle);
//            tv_headtitle.setText("美丽南昌 幸福家园");
        }
        fragment_first_bannera = (XBanner) view.findViewById(R.id.fragment_first_bannera);
        fragment_first_scrollView = (PullToRefreshScrollView) view.findViewById(R.id.fragment_first_scrollView);
        fragment_first_scrollView.setMode(PullToRefreshBase.Mode.BOTH);
        fragment_first_scrollView.requestFocus();
        fragment_first_scrollView.setFocusable(true);
        fragment_first_scrollView.setFocusableInTouchMode(true);
        fragment_first_sqzu_ckqb_llt = (LinearLayout) view.findViewById(R.id.fragment_first_sqzu_ckqb_llt);
        fragment_first_sqzu_ckqb_llt.setOnClickListener(this);

        fragment_first_head_sida_gongnneg = (GridView) view.findViewById(R.id.fragment_first_head_sida_gongnneg);
        fragment_first_listView = (MyListView) view.findViewById(R.id.fragment_first_listView);
        Tools.showScrollRefreshView(fragment_first_scrollView);
        //轮播图点击事件
        fragment_first_bannera.setOnItemClickListener(new XBanner.OnItemClickListener() {
            @Override
            public void onItemClick(XBanner banner, int position) {
                Intent intent = new Intent(context, InfoDetailActivity.class);
                intent.putExtra("id", homeBannerList.get(position).getId());
                intent.putExtra("flag","BannerDetailFlag");
                context.startActivity(intent);
            }
        });
        fragment_first_scrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ScrollView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ScrollView> refreshView) {
                // 处理下拉刷新的业务
                if (refreshView.getCurrentMode().equals(PullToRefreshBase.Mode.PULL_FROM_START)) {
                    isfresh = true;
                    Tools.showScrollRefreshView(fragment_first_scrollView);
                    skip = 0;
                    getBannerData();
                    contributorPresenter.getLookList(cidNumber, "0", skip, limit, HOME_NEWS);
                }
                // 处理上拉刷新的业务
                else {
                    isfresh = false;
                    Tools.showScrollRefreshView(fragment_first_scrollView);
                    skip += limit;
                    //首页资讯
                    contributorPresenter.getLookList(cidNumber, "0", skip, limit, HOME_NEWS);
                }
            }
        });

        fragment_first_listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                LookHomeNews lookHomeNews=homeNewsList.get(position);
                Intent intent = new Intent(context, InfoDetailActivity.class);
                intent.putExtra("id", lookHomeNews.getId());
                intent.putExtra("flag",SelectedIndustryFragment.class.getSimpleName());
                intent.putExtra("title",lookHomeNews.getTitle());
                startActivity(intent);
            }
        });

        //四大模快ItemClick点击事件
        fragment_first_head_sida_gongnneg.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String name=homeModuleFourList.get(position).getTitle();
                if(name.equals("社区活动"))
                {
                    Intent intent = new Intent(context, FloorEventActivity.class);
                    intent.putExtra("name",name);
                    intent.putExtra("cid",cidNumber);
                    intent.putExtra("type",0);
                    startActivity(intent);
                }else if(name.equals("办事窗口"))
                {
                    Intent intent=new Intent(context, ReceptionCenterActivity.class);
                    intent.putExtra("id",cidNumber);
                    intent.putExtra("name",name);
                    startActivity(intent);
                }else if(name.equals("生活服务"))
                {
                    Intent intent=new Intent(context, LifeServerActivity.class);
                    intent.putExtra("id",cidNumber);
                    intent.putExtra("name",name);
                    startActivity(intent);
                }else if(name.equals("我有话说"))
                {
                    boolean isLogin=Tools.getSharedPreferencesboolen(Constant.isLoginIn,false,context);
                    if(isLogin)
                    {
                        Intent intent=new Intent(context,PeopleControlPublishActivity.class);
                        intent.putExtra("cid",cidNumber);
                        startActivity(intent);
                    }else
                    {
                        iphoneDialogBuilder idb = new iphoneDialogBuilder(context);
                        idb.setTitle("提示");
                        idb.setMessage("是否登录");
                        idb.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                Intent intent = new Intent(context, Login_RegisterActivity.class);
                                myApplication.setSourceIntoLoginRegisterActivity(HomeActivity.class.getSimpleName());
                                startActivity(intent);

                            }
                        });
                        idb.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {

                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        idb.show();
                    }
                }

            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mCallBack = (ClickIntoFragment) context;
    }

    //处理Banner图片
    private void getBannerData() {

        if(streetInfoListBean==null)
        {
            String city= myApplication.getLocationCity();
            String country=myApplication.getLocationDistrict();
            contributorPresenter.getHomeFetchStreet(city,country,LOCATION_FLAG);
        }

        if(cidNumber!=null)
        {
            contributorPresenter.getHomeBanner(cidNumber, HOME_BANNER);
            //四大功能
             contributorPresenter.getHomeModuleList(cidNumber,0, FOUR_MODULE);
            //八大功能
             contributorPresenter.getHomeModuleList(cidNumber,1, EIGHT_MODULE);
            //首页资讯

            if(quanBuAdapter==null || quanBuAdapter.getCount()==0)
            {
                contributorPresenter.getLookList(cidNumber, "0", skip, limit, HOME_NEWS);
            }

        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.fragment_first_sqzu_ckqb_llt:
                mCallBack.clickIntoFragment();
                break;
            case R.id.layout_one:
                Intent intent=new Intent(context, ShangjiaCuXiaoActivity.class);
                intent.putExtra("id",cidNumber);
                intent.putExtra("name","商家促销");
                startActivity(intent);
                break;
            case R.id.layout_two:
                // 百姓监督
                Intent intentpepl = new Intent(context, PeopleControlActivity.class);
                intentpepl.putExtra("name","百姓监督");
                intentpepl.putExtra("cid",cidNumber);
                startActivity(intentpepl);
                break;
            case R.id.layout_three:
                //楼宇活动
                Intent intentthree = new Intent(context, FloorEventActivity.class);
                intentthree.putExtra("name","楼宇活动");
                intentthree.putExtra("cid",cidNumber);
                intentthree.putExtra("type",0);
                startActivity(intentthree);
                break;
        }
    }

    @Override
    public void onLoadContributorStart(String flag) {

    }

    @Override
    public void onLoadContributorSuccess(String jsonString, String flag) {
        try {
            //banner
            if (flag.equals(HOME_BANNER)) {

                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    homeBannerList = JsonTools.jsonStringToList(jsonMessage, HomeBanner.class);
                    List<String> titleList = new ArrayList<>();
                    List<String> purlList = new ArrayList<>();
                    for (int i = 0; i < homeBannerList.size(); i++) {
                        purlList.add(homeBannerList.get(i).getImg());
                        titleList.add(homeBannerList.get(i).getTitle());
                    }
                    fragment_first_bannera.setData(purlList, titleList);
                    fragment_first_bannera.setPoinstPosition(XBanner.RIGHT);//指示器居于右侧
                    fragment_first_bannera.setmAdapter(this);
                }

            } else if (flag.equals(FOUR_MODULE)) {
//                Log.e("http地址：", jsonString);
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    homeModuleFourList = JsonTools.jsonStringToList(jsonMessage, HomeModule.class);
                    if (homeModuleFourList != null && homeModuleFourList.size() > 0) {
                        FourModuleNewAdapter siDaGongNengAdapter = new FourModuleNewAdapter(context, homeModuleFourList);
                        fragment_first_head_sida_gongnneg.setAdapter(siDaGongNengAdapter);
                    }

                }
            }else if(flag.equals(EIGHT_MODULE))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    homeModuleEightList = JsonTools.jsonStringToList(jsonMessage, HomeModule.class);
                    if (homeModuleEightList != null && homeModuleEightList.size() > 0) {
                        viewthree.setVisibility(View.VISIBLE);
                        layout_threenew.setVisibility(View.VISIBLE);
                        HomeModule homeModuleone=homeModuleEightList.get(0);
                        tv_titleone.setText(homeModuleone.getTitle());
                        tv_contentone.setText(homeModuleone.getContent());
                        Glide.with(context).load(homeModuleone.getIcon())
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into((ImageView) iv_one);


                        HomeModule homeModuletwo=homeModuleEightList.get(1);
                        tv_titletwo.setText(homeModuletwo.getTitle());
                        tv_contenttwo.setText(homeModuletwo.getContent());
                        Glide.with(context).load(homeModuletwo.getIcon())
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into((ImageView) iv_two);


                        HomeModule homeModulethree=homeModuleEightList.get(2);
                        tv_titlethree.setText(homeModulethree.getTitle());
                        tv_contentthree.setText(homeModulethree.getContent());
                        Glide.with(context).load(homeModulethree.getIcon())
                                .diskCacheStrategy(DiskCacheStrategy.ALL)
                                .into((ImageView) iv_three);
                    }

                }
            }
            else if (flag.equals(HOME_NEWS)) {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code = respObj.getCode();
                Object object = respObj.getMessage();
                if (code.equals("200") && object != null) {
                    String jsonMessage = JsonTools.objectToJsonString(object);
                    List<LookHomeNews> homeNewsItem = JsonTools.jsonStringToList(jsonMessage, LookHomeNews.class);
                    if (homeNewsItem != null && homeNewsItem.size() > 0) {
                        if (isfresh) {
                            homeNewsList = homeNewsItem;
                            quanBuAdapter = new LookListAdapter(context, homeNewsList);
                            fragment_first_listView.setAdapter(quanBuAdapter);
                        } else {
                            homeNewsList.addAll(homeNewsItem);
                            quanBuAdapter.notifyDataSetChanged();
                            fragment_first_listView.setSelection(homeNewsList.size());
                        }

                    }

                }
            }else if(flag.equals(LOCATION_FLAG))
            {
                RespObj respObj = JsonTools.jsonStringToObject(jsonString, RespObj.class);
                String code=respObj.getCode();
                if(code.equals("200"))
                {
                    String message=JsonTools.objectToJsonString(respObj.getMessage());
                    List<StreetInfoListBean> listData=JsonTools.jsonStringToList(message,StreetInfoListBean.class);
                    if(listData!=null &&listData.size()>0)
                    {
                        Tools.setSharedPreferencesStrings(Constant.SharePreferenceLocation,JsonTools.objectToJsonString(listData.get(0)),context);
                        streetInfoListBean=listData.get(0);
                        cidNumber=streetInfoListBean.getId();
                        cidTitle=streetInfoListBean.getStreetName();
                        tv_headtitle.setText(cidTitle);
                        contributorPresenter.getHomeBanner(cidNumber, HOME_BANNER);
                        //四大功能
                        contributorPresenter.getHomeModuleList(cidNumber,0, FOUR_MODULE);
                        //八大功能
                        contributorPresenter.getHomeModuleList(cidNumber,1, EIGHT_MODULE);
                        //首页资讯
                        contributorPresenter.getLookList(cidNumber, "0", skip, limit, HOME_NEWS);
                    }
                }
            }

        } catch (Exception e) {

        }
    }

    @Override
    public void onLoadContributorComplete(String flag) {
        fragment_first_scrollView.onRefreshComplete();
    }

    @Override
    public void onLoadContributorError(String error, String flag) {

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        ishide = hidden;
        if (hidden) {
        } else {
            isfresh = true;
            skip = 0;
            getBannerData();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(HomeFragment.class.getSimpleName());
    }

    @Override
    public void onResume() {
        super.onResume();
        if (ishide) {

        } else {
            isfresh = true;
            skip = 0;
            getBannerData();
        }
        MobclickAgent.onPageStart(HomeFragment.class.getSimpleName());
    }


    //XBanner处理轮播图片，文字
    @Override
    public void loadBanner(XBanner banner, Object model, View view, int position) {
        try {
            Glide.with(context).load(homeBannerList.get(position).getImg())
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into((ImageView) view);
        }catch (Exception e)
        {

        }
    }
}
